<?php

namespace App\Console\Commands\Renew;

use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class MerchantCloseOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'merchantOrder:closeExpiredMerchantOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '商户通：关闭超时未处理的订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //2023-10-24
        //2023-09-21
        //2023-09-06
        //2023-08-24
        OpenShopSpaceDesignCostMappingModel::query()->where(function ($query) {
            $query->where(function ($query) {
                $date = Carbon::createFromDate("2023-08-24");
                $query->where("createdAt", ">=", $date->copy()->startOfDay()->timestamp)
                      ->where("createdAt", "<=", $date->copy()->endOfDay()->timestamp);
            })->orWhere(function ($query) {
                $date = Carbon::createFromDate("2023-09-06");
                $query->where("createdAt", ">=", $date->copy()->startOfDay()->timestamp)
                      ->where("createdAt", "<=", $date->copy()->endOfDay()->timestamp);
            })->orWhere(function ($query) {
                $date = Carbon::createFromDate("2023-09-21");
                $query->where("createdAt", ">=", $date->copy()->startOfDay()->timestamp)
                      ->where("createdAt", "<=", $date->copy()->endOfDay()->timestamp);
            })->orWhere(function ($query) {
                $date = Carbon::createFromDate("2023-10-24");
                $query->where("createdAt", ">=", $date->copy()->startOfDay()->timestamp)
                      ->where("createdAt", "<=", $date->copy()->endOfDay()->timestamp);
            });
        })->where(
            "payStatus", 0
        )->where("createdByUid", 0
        )->chunkById(30, function (Collection $collection) {
            $collection->each(function (OpenShopSpaceDesignCostMappingModel $costMappingModel) {
                try {
                    $this->output->info($costMappingModel->preparationNo);
                    SpaceDesignService::closeCostOrder($costMappingModel->preparationNo);
                } catch (\Exception $exception) {
                    $this->output->error("{$costMappingModel->preparationNo} - " . $exception->getMessage());
                }
            });
        });
        return 0;
    }
}
